package com.tecklab.demo.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.tecklab.demo.aspect.OperateLog;
import com.tecklab.demo.common.Result;
import com.tecklab.demo.dto.LoginResult;
import com.tecklab.demo.entity.UserEntity;
import com.tecklab.demo.param.LoginRequest;
import com.tecklab.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/api/auth")
public class LoginController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    @OperateLog(optName = "用户登录", optType = "登录")
    public Result<LoginResult> login(@RequestBody LoginRequest request) {
        try {
            // 验证用户凭据
            UserEntity user = userService.login(request.getUsername(), request.getPassword());
            if (user != null && StringUtils.equals(request.getPassword(), user.getPassword())) {
                StpUtil.login(user.getId());
                StpUtil.getTokenSession().set("user", user);
                LoginResult loginResult = new LoginResult();
                loginResult.setUserInfo(user);
                loginResult.setToken(StpUtil.getTokenValue());
                return Result.success(loginResult);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            log.error("登录过程中发生错误", e);
            return Result.error("登录过程中发生错误");
        }
    }

    @PostMapping("/logout")
    @OperateLog(optName = "用户登出", optType = "登出")
    public Result<?> logout() {
        StpUtil.logout();
        return Result.success();
    }
}